/**
 * Version: 1.0.0
 */
(function (domGlobals) {
  'use strict';

  var formDataArr = [];
  var global$1 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK');
  var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  var contextSelectedElement;

  var Api = { get: function (editor) {
      return {
        getAllElement: function () {
          for (var id in formDataArr) {
            if(!editor.dom.doc.getElementById(id)) {
              delete formDataArr[id];
            }
          }
          return formDataArr;
        },
        setAllElement: function(data) {
          formDataArr = data;
        }
      };
    }
  };

  var Utils = {
    isText:  function (elm) {
      return elm && elm.nodeName === 'INPUT' && elm.type === 'text';
    },
    hasTexts: function (elements) {
      return global$3.grep(elements, Utils.isText).length > 0;
    },
    deleteText: function (editor) {
      editor.undoManager.transact(function () {
        var selectedElement = Utils.getSelectedText(editor);
        if (selectedElement) {
          editor.dom.remove(selectedElement, true);
        }
        editor.focus();
      });
    },
    getSelectedData: function(id) {
      return formDataArr[id];
    },
    getSelectedText: function (editor) {
      if(editor.selection && contextSelectedElement && Utils.getSelectedData(contextSelectedElement.id)) {
        return contextSelectedElement;
        //return editor.dom.getParents(contextSelectedElement, 'input');
      }
      contextSelectedElement = null;
      /*if(editor.selection) {
        return editor.dom.getParent(editor.selection.getStart(), 'input[type=date]');
      }*/
      return null;
    }
  };

  var Dialog = {
    //元素属性
    updateElement: function (editor, selectedElement, elementAttrs) {
      editor.focus();
      editor.dom.setAttribs(selectedElement, elementAttrs);
      editor.selection.select(selectedElement);
    },
    createElement: function (editor, elementAttrs) {
      editor.focus();
      editor.insertContent(editor.dom.createHTML('input type="text"', elementAttrs));
    },
    getInitialData : function (editor, isAdd) {
      if(!isAdd) {
        var selectedText = Utils.getSelectedText(editor);
        if(selectedText) {
          var selectedData = Utils.getSelectedData(selectedText.id);
          return {
            id: selectedData.id,
            title: selectedData.title,
            width: selectedData.width || '150',
            value: selectedData.value,
            requireFlag: Boolean(selectedData.requireFlag)
          };
        }
      }
      contextSelectedElement = null;
      return {
        id: 'text-' + new Date().getTime(),
        title: '文本控件',
        width: '150',
        value: '',
        requireFlag: true,
      };
    },
    open: function (editor, isAdd) {
      var body = {
        type: 'panel',
        items: [
          {
            type: 'bar',
            items: [
              {
                name: 'title',
                type: 'input',
                label: '控件名称'
              },
              {
                name: 'value',
                type: 'input',
                label: '默认值'
              }
            ]
          },{
            type: 'bar',
            items: [
              {
                name: 'width',
                type: 'input',
                label: '宽度',
                inputMode: 'numeric'
              },
              {
                name: 'requireFlag',
                type: 'checkbox',
                label: '是否必填'
              }
            ]
          }]
      };
      var initData = Dialog.getInitialData(editor, isAdd);
      return editor.windowManager.open({
        title: '文本控件新增/编辑',
        size: 'normal',
        body: body,
        buttons: [
          {
            type: 'cancel',
            name: 'cancel',
            text: 'Cancel'
          },
          {
            type: 'submit',
            name: 'save',
            text: 'Save',
            primary: true
          }
        ],
        initialData: initData,
        onChange: function (api, _a) {
          var name = _a.name;
          /*dialogDelta.onChange(api.getData, { name: name }).each(function (newData) {
            api.setData(newData);
          });*/
        },
        onSubmit: function (api) {
          var data = api.getData();
          var selectedElement = Utils.getSelectedText(editor);
          var elementAttr = data;
          elementAttr.style = 'width:' + data.width + 'px;';
          elementAttr.id = initData.id;

          editor.undoManager.transact(function () {
            if (selectedElement) {
              Dialog.updateElement(editor, selectedElement, elementAttr);
            } else {
              Dialog.createElement(editor, elementAttr);
            }
          });
          formDataArr[elementAttr.id] = elementAttr;
          api.close();
        }
      });
    }
  };

  var Actions = {
    openDialog: function (editor, isAdd) {
      return function() {
        Dialog.open(editor, isAdd);
      };
    },
    gotoSelectedText: function (editor) {
      return function () {
        Actions.gotoText(editor, Utils.getSelectedText(editor));
      };
    },
    gotoText:  function (editor, a) {
      if (a) {
        var targetEl = a;
        if (targetEl.length) {
          editor.selection.scrollIntoView(targetEl[0], true);
        }
      }
    },
    toggleEnabledState: function (editor) {
      return function (api) {
        if(contextSelectedElement) {
          api.setDisabled(!Utils.hasTexts(editor.dom.getParents(contextSelectedElement, 'input')));
          var nodeChangeHandler = function (e) {
            return api.setDisabled(!Utils.hasTexts(e.parents));
          };
          editor.on('NodeChange', nodeChangeHandler);
          return function () {
            return editor.off('NodeChange', nodeChangeHandler);
          };
        }
      };
    }
  };

  var Controls = {
    //setupButtons: setupButtons,
    setupMenuItems: function (editor) {
      editor.ui.registry.addMenuItem('formtext-add', {
        text: '文本控件',
        //shortcut: 'Meta+K',
        onAction: Actions.openDialog(editor, true)
      });
      editor.ui.registry.addMenuItem('formtext-edit', {
        text: '编辑文本控件',
        icon: 'edit-block',
        onAction: Actions.openDialog(editor, false),
        onSetup: Actions.toggleEnabledState(editor)
      });

      editor.ui.registry.addMenuItem('formtext-del', {
        icon: 'remove',
        text: '删除文本控件',
        onAction: function () {
          return Utils.deleteText(editor);
        },
        onSetup: Actions.toggleEnabledState(editor)
      });
    },
    setupContextMenu: function(editor) {
      editor.ui.registry.addContextMenu('formtext', {
        update: function(element) {
          if(Utils.hasTexts(editor.dom.getParents(element, 'input'))) {
            contextSelectedElement = element;
            return 'formtext-edit formtext-del';
          }
          return  '';
        }
      });
    }
  };

  function Plugin () {
    global$1.add('formtext', function (editor) {
      Controls.setupMenuItems(editor);
      Controls.setupContextMenu(editor);
      return Api.get(editor);
    });
  }

  Plugin();

}(window));
